<script setup lang='ts'>
import { CreditCard } from '@element-plus/icons-vue'
import { useCheckUser, useGetDetail, useProfileSave } from '@fl/api/man-api/jc-authentication'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { getCurrentInstance, ref, toRaw, unref } from 'vue'
import { useRoute } from 'vue-router'

import RemitItem from './remit-item.vue'
import { useRule } from './use-rule'
import { useStep } from './use-step'

const { createErrorModal } = useMessage()

const { data } = useGetDetail()

const instance = getCurrentInstance()
const { rules } = useRule(instance)
const route = useRoute()
const { stepMove } = useStep()

const detail = ref<any>({})
const isApproval = ref(false)
const finishFormRef = ref()
const authType: any = route.query?.authType ?? 1

const isFrMode = authType === '0' // 是否法人认证

const form = ref({
    accountName: '',
    accountNumber: '',
    bankName: '',
    idCardBack: '',
    idCardFront: '',

    legalPersonCardNo: '',
    legalPersonName: '',
    legalPersonPhone: '',
})

const colums: any = [
    {
        columns: [
            {
                colProps: {
                    span: 24,
                },
                label: '法人身份证',
                prop: 'fdsfz',
            },
            {
                fieldProps: computed(() => (
                    {
                        disabled: import.meta.env.VITE_NODE_ENV === 'prod',
                    }
                )),
                label: '法人姓名',
                prop: 'legalPersonName',
            },
            {

                label: '法人身份证',
                prop: 'legalPersonCardNo',
            },
            {

                label: '法人手机号',
                prop: 'legalPersonPhone',
                renderExtra: () => `法人实名手机号`,
            },
        ],
        title: '法人信息',
    },
    {},
    {
        columns: [
            {
                label: '开户名称',
                prop: 'accountName',
                renderExtra: () => `对公账户需跟主体证件上的机构名称保持一致`,
            },
            {
                label: '开户银行',
                prop: 'bankName',
            },
            {
                label: '银行账户',
                prop: 'accountNumber',
                renderExtra: () => `后续需用对公账户向我司汇入一笔指定金额，请填写真实有效的对公账户`,
            },
        ],
        title: '填写账户信息                                         ',
    },
]

const getTitle = computed(() => {
    return ['企业法人三要素认证', '', '企业对公打款认证'][authType]
})

const group = computed(() => {
    return [colums[authType]]
})

const { isPending: userLoading, mutate: checkUserMutate } = useCheckUser()

const { isPending, mutate } = useProfileSave()

async function doSave() {
    // 1.表单校验
    const isValid = await finishFormRef.value.formInstance.formInstance.validate()

    if (!isValid)
        return

    // 2. 校验第二步联系人信息
    const { contactCardNo, contactMobile, contactName } = detail.value
    checkUserMutate({ contactCardNo, contactMobile, contactName }, {
        onError: () => {
            createErrorModal({ content: '认证联系人信息不一致，请返回上一步检查！' })
        },
        onSuccess: () => {
            if (isFrMode) {
                // 3. 校验法人信息
                const { legalPersonCardNo, legalPersonName, legalPersonPhone } = form.value
                checkUserMutate({ contactCardNo: legalPersonCardNo, contactMobile: legalPersonPhone, contactName: legalPersonName }, {
                    onError: (err: any) => {
                        createErrorModal({ content: err })
                    },
                    onSuccess: () => {
                        // 4.真正的提交
                        doSubmit()
                    },
                })
            }
            else {
                // 对公账户认证 直接提交
                doSubmit()
            }
        },
    })
}

function doSubmit() {
    const { accountName, accountNumber, bankName, idCardBack, idCardFront, legalPersonCardNo, legalPersonName, legalPersonPhone } = form.value
    const target = { ...detail.value, authType: Number.parseInt(authType), bankAccount: {}, isDraft: 0, legalPersonAuth: {} }

    if (isFrMode) {
        target.legalPersonAuth = {
            idCardBack,
            idCardFront,
            legalPersonCardNo,
            legalPersonName,
            legalPersonPhone,
        }
        target.legalRepresentative = legalPersonName
    }
    else {
        target.bankAccount = {
            accountName,
            accountNumber,
            bankName,
        }
        target.isDraft = 1 // 对公打款 设置为草稿状态，后续打款成功后提交
        target.isPaySubmit = 1
    }

    mutate(target, {
        onError: (e) => {
            createErrorModal({ content: e as unknown as string })
        },
        onSuccess: () => {
            ElMessage.success('保存成功')

            // 法人认证提交成功后 去到结果页
            if (isFrMode)
                stepMove({ auditStatus: 3, step: 4 })
            else
                isApproval.value = true // 对公打款 去到打款页面
        },
    })
}

function upStep() {
    window.sessionStorage.setItem('FINISH_FORM_DATA', JSON.stringify(form.value))
    stepMove({ authType, step: 2 })
}
// 拉取缓存
function getCache() {
    // const str = window.sessionStorage.getItem('FINISH_FORM_DATA')
    // if (str) {
    //     return JSON.parse(str)
    // }
    return {}
}

watchEffect(() => {
    if (data.value) {
        detail.value = data.value
        const bankAccount = data.value.bankAccount ?? {}
        const { accountName, accountNumber, bankName } = bankAccount

        const legalPersonAuth = data.value.legalPersonAuth ?? {}
        const { idCardBack, idCardFront, legalPersonCardNo, legalPersonName, legalPersonPhone } = legalPersonAuth
        let formData = {}
        // 回显信息
        if (detail.value.authType === 0) {
            formData = {
                idCardBack: idCardBack ?? '',
                idCardFront: idCardFront ?? '',
                legalPersonCardNo: legalPersonCardNo ?? '',
                legalPersonName: legalPersonName ?? '',
                legalPersonPhone: legalPersonPhone ?? '',
            }
        }
        if (detail.value.authType === 2) {
            formData = {
                accountName: accountName ?? '',
                accountNumber: accountNumber ?? '',
                bankName: bankName ?? '',
            }
        }

        form.value = {
            ...form.value,
            legalPersonName: data.value.legalRepresentative, // 法人姓名回显
            ...getCache(),
            ...formData,

        }
    }
})
defineExpose({
    form,
})
</script>

<template>
    <p class="mb-20 mt-40 text-24 c-#DA0004 font-600 flex items-center">
        <el-icon>
            <CreditCard />
        </el-icon>

        <span class="ml-13">{{ getTitle }}</span>
    </p>

    <template v-if="!isApproval">
        <SearchForm ref="finishFormRef"
                    v-model="form"
                    :has-footer="false"
                    :group="group"
                    :rules="rules"
                    label-position="top"
        >
            <template #group-header="{ title }">
                <div class="text-20 font-600">
                    <span>{{ title }}</span>
                </div>
            </template>

            <template #plus-field-fdsfz>
                <el-row class="upload_box min-h-180 w-full">
                    <el-col :span="6">
                        <FlUpload v-model="form.idCardFront"
                                  class="front_upload"
                                  hide-plus-icon
                                  accept=".png,.jpg,.jpeg"
                                  :file-size="10"
                                  tips="身份证人像面"
                        />
                    </el-col>

                    <el-col :span="6">
                        <FlUpload v-model="form.idCardBack"
                                  class="back_upload"
                                  accept=".png,.jpg,.jpeg"
                                  hide-plus-icon
                                  :file-size="10"
                                  tips="身份证国徽面"
                        />
                    </el-col>
                </el-row>
            </template>
        </SearchForm>

        <div class="text-center">
            <ElButton v-loading.fullscreen.lock="isPending"
                      class="mb-30 mt-20"
                      @click="upStep"
            >
                上一步
            </ElButton>

            <ElButton class="mb-30 mt-20"
                      type="primary"
                      :loading="userLoading"
                      @click="doSave"
            >
                提交
            </ElButton>
        </div>
    </template>

    <RemitItem v-else
               :data="detail"
    />
</template>

<style lang="less" scoped>
.upload_box {
    :deep(.el-upload--picture-card) {
        width: 270px !important;
        height: 160px !important;
        background-repeat: no-repeat;
        background-size: 100% 100%;
    }

    :deep(.el-upload-list__item) {
        width: 270px !important;
        height: 160px !important;
    }

    :deep(.front_upload) {
        .el-upload--picture-card {
            background-image: url('https://public-obs-cdn.anjulian.com.cn/2024-06-20/296d7475-46f3-4e91-8c62-9b40c089b96e.png');
        }

        .el-upload__tip {
            padding-left: 100px;
            margin-top: -12px;
        }
    }

    :deep(.back_upload) {
        .el-upload--picture-card {
            background-image: url('https://public-obs-cdn.anjulian.com.cn/2024-06-20/07803f19-9af4-4bb1-bb06-888c14fbe5c4.png');
        }

        .el-upload__tip {
            padding-left: 100px;
            margin-top: -12px;
        }
    }
}
</style>
